﻿using RentACarRESTApi.Models;
using RentACarRESTApi.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Mvc;

namespace RentACarRESTApi.Controllers
{
    public class CarsController : ApiController
    {
        CarsRepository carsRepository = new CarsRepository();

        public IEnumerable<Car> Get()
        {
            return carsRepository.GetCars();
        }

        public Car Get(int id)
        {
            return carsRepository.GetCarById(id);
        }

        public IEnumerable<AvailabilityResponse> Get([FromUri] DateTime startDate, [FromUri] DateTime endDate)
        {
            ReservationsRepository reservationRepository = new ReservationsRepository();

            List<AvailabilityResponse> availList = new List<AvailabilityResponse>();

            foreach (Car car in carsRepository.GetCars())
            {
                
                bool found = reservationRepository.ContainsReservationCarBetweenDates(car.ID, startDate, endDate);
                if (!found)
                {
                    string idStr = car.ID.ToString() + "/" + startDate.ToString("MM-dd-yyyy") + "/" + endDate.ToString("MM-dd-yyyy");
                    AvailabilityResponse availResp = new AvailabilityResponse(car, startDate, endDate);
                    availResp.Links.Add(new Link(rel: "/linkrels/reservations/reserve", uri: "/api/reservations/" + idStr));
                    availResp.Links.Add(new Link(rel: "/linkrels/cars/" + car.ID + "/details", uri: "/api/cars/" + car.ID));
                    availList.Add(availResp);
                }
            }

            return availList;
        }
    }
}
